package com.example.cart.application;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import androidx.room.Room;
import androidx.room.RoomDatabase;

import com.example.cart.database.ShoppingDatabase;
import com.example.cart.entity.Product;
import com.example.cart.utils.FileUtils;

import java.io.File;
import java.util.List;
import java.util.Objects;

import lombok.Getter;

public class CustomApplication extends Application {

    @Getter
    private static CustomApplication instance;

    @Getter
    private ShoppingDatabase shoppingDatabase;

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;

        // 初始化购物车数据库对象
        shoppingDatabase = Room.databaseBuilder(this, ShoppingDatabase.class, "cart")
                .allowMainThreadQueries()
                .build();

        initProducts();
    }

    /**
     * 初始化商品信息。将商品信息存到SQLite数据库中
     */
    public void initProducts() {
        // 判断app是不是安装后的首次启动
        SharedPreferences sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);
        boolean launched = sharedPreferences.getBoolean("launched", false);
        if (launched) {
            Log.d("CustomApplication", "App不是第一次启动，不需要再执行商品信息初始化。");
            return;
        }
        // 获取当前App的私有下载目录
        String dir = Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)).toString() + File.separator;
        List<Product> productList = Product.getInitialProductList();
        // 处理图片资源，将图片资源拷贝到SD卡中，生成图片路径
        for (Product product : productList) {
            // product.pic中保存的是图片资源的ID-R.drawable.xxx
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), product.getPic());
            String fileName = product.getPicPath() + "-" + System.currentTimeMillis() + ".jpeg";
            String path = dir + fileName;
            FileUtils.saveImage(bitmap, path);
            product.setPicPath(path);
        }
        shoppingDatabase.initProducts(productList);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("launched", true);
        editor.apply();
    }


}
